package com.yaoyong.yy_demo.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

public class ImageUtil {

    private static final int WIDTH = 120;
    private static final int HEIGHT = 30;

    public static void randomImage() throws IOException {
        // 实现需要在内存中构建一张图片
        BufferedImage br = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

        //首先 换背景
        // 拿到 可以操作图片的对象
        Graphics2D graphics = (Graphics2D) br.getGraphics();

        //设置 颜色
        graphics.setColor(Color.WHITE);
        //填充颜色
        graphics.fillRect(0, 0, WIDTH, HEIGHT);

        String base ="ABCDEFGHIJKLMN";
        Random rand = new Random();

        //画4 个字符上去

        //设置画字符的颜色
        graphics.setColor(Color.RED);
        graphics.setFont(new Font("宋体", Font.BOLD, 18));
        int m =20;
        for (int i = 0; i < 4; i++) {

            // 随机取到 一个脚标
            int index = rand.nextInt(base.length());

            char charAt = base.charAt(index);

            // -30 +30

            int jiaodu = rand.nextInt(60)-30;

            double theta = jiaodu*Math.PI/180;

            graphics.rotate(theta,m, 20);
            graphics.drawString(charAt+"", m, 20);
            graphics.rotate(-theta,m, 20);

            m+=20;
        }

        //指定线的颜色
        graphics.setColor(Color.GREEN);

        //画 4 条干扰线
        for (int i = 0; i < 4; i++) {

            int x1 = rand.nextInt(WIDTH);
            int x2 = rand.nextInt(WIDTH);
            int y1 = rand.nextInt(HEIGHT);
            int y2 = rand.nextInt(HEIGHT);

            graphics.drawLine(x1, y1, x2, y2);

        }

        ImageIO.write(br, "png", new FileOutputStream("xxx.png"));
    }
}
